/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gskorupa.univermon.auth;

import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author greg
 */
public class UsersServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {

        //
        resp.setContentType("application/json");
        Gson gson = new Gson();
        String uid = req.getPathInfo();
        if (uid != null) {
            if (uid.startsWith("/")) {
                uid = uid.substring(1);
            }
        }
        String action = req.getParameter("action");
        if (action == null) {
            action = "";
        }

        if (uid == null) {
            if (action.isEmpty()) {
                resp.getWriter().println(uid);
            } else if (action.equalsIgnoreCase("register")) {
                // todo: authorization
                // add user
                String email = req.getParameter("email");
                String secretKey = req.getParameter("secret");
                String newUid = HashMaker.md5Java(secretKey + "@" + email);
                Client newUser = new Client();
                newUser.setUid(newUid);
                newUser.setConfirmed(true);
                int result = RegisteredClients.getInstance().add(newUser);

                if (result == RegisteredClients.OK) {
                    resp.getWriter().println(gson.toJson(newUser));
                }
            } else if (action.equalsIgnoreCase("find")) {
                // todo: authorization
            }
        } else {
            if (action.isEmpty()) {
                Client user = RegisteredClients.getInstance().get(uid);
                //send response
                if (user != null) {
                    resp.getWriter().println(gson.toJson(user));
                } else {
                    resp.sendError(501, "user not registered");
                }
            } else if (action.equalsIgnoreCase("adddevice")) {

            } else if (action.equalsIgnoreCase("removedevice")) {

            } else if (action.equalsIgnoreCase("confirmregistration")) {

            } else if (action.equalsIgnoreCase("unregister")) {

            } else if (action.equalsIgnoreCase("confirmunregister")) {

            } else {
                //unknown action
            }
        }
    }

    private int register(String email, String secret) {
        return 0;
    }
}
